package com.kaibes.module.file.local.listener;

import java.io.File;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.kaibes.core.base.util.FileUtils;
import com.kaibes.module.file.local.FileConfig;
import com.kaibes.module.file.local.db.FileInfo;
import com.kaibes.module.file.local.db.FileInfoService;
import com.kaibes.module.file.local.db.FileMarkService;
import com.kaibes.orm.core.listener.DeleteListener;
import com.kaibes.orm.curd.Delete;
import com.kaibes.orm.spring.OrmListener;

@OrmListener(service = FileInfoService.class)
public class FileInfoDeleteListener implements DeleteListener {

    @Autowired
    private FileConfig fileConfig;
    @Autowired
    private FileInfoService fileInfoService;
    @Autowired
    private FileMarkService fileMarkService;
    
    private ThreadLocal<List<FileInfo>> threadLocal = new ThreadLocal<>();
    
    @Override
    public void beforeDelete(Delete delete) throws SQLException {
        List<FileInfo> fileInfos = fileInfoService.list(delete.getQueries());
        if (!fileInfos.isEmpty()) {
            threadLocal.set(fileInfos);
        }
    }
    
    @Override
    public void afterDelete(Delete delete, int count) throws SQLException {
        List<FileInfo> fileInfos = threadLocal.get();
        threadLocal.set(null);
        for (FileInfo fileInfo : fileInfos) {
            File file = new File(fileInfo.getPath());
            if (file.exists()) {
                file.delete();
                String filename = file.getName();
                filename = filename.substring(0, filename.lastIndexOf("."));
                String path = fileConfig.getCache()+filename;
                FileUtils.delete(new File(path));
            }
        }
        fileMarkService.clearCache();
    }
    
}
